<template>
  <div>
    <el-dialog ref="batchSend" title="批量派遣" :visible="popVisible" :close-on-click-modal="false" @close="onCancel">
      <el-form ref="sendForm" label-width="120px" label-position="left" :model="sendForm" :rules="formRules">
        <el-form-item :required="true" label="选择用工单位" prop="tenantId">
          <el-select placeholder="请选择用工单位" name="tenantId" v-model="sendForm.tenantId" :loading="loading">
            <el-option v-for="item in tenantList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :required="true" label="派遣开始时间" prop="startTime">
          <el-date-picker v-model="sendForm.startTime" type="datetime" placeholder="选择派遣开始时间" :picker-options="startPickerOptions"> </el-date-picker>
        </el-form-item>
        <el-form-item :required="true" label="派遣结束时间" prop="endTime">
          <el-date-picker v-model="sendForm.endTime" type="datetime" placeholder="选择派遣结束时间" :picker-options="endPickerOptions"> </el-date-picker>
        </el-form-item>
      </el-form>
      <p>将对以下{{ list.length }}个人员发起派遣：</p>

      <el-table :data="list" element-loading-text="加载中" border fit highlight-current-row>
        <el-table-column type="index" min-width="80" label="序号" align="center"></el-table-column>

        <el-table-column
          :label="item.label"
          :show-overflow-tooltip="item.showTips"
          v-for="item in columns"
          :key="item.key"
          :align="item.align || 'center'"
        >
          <template slot-scope="scope">
            <span v-if="item.key === 'gender'">{{ scope.row[item.key] | genderFilter }}</span>
            <span v-else>{{ scope.row[item.key] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="form-footer" slot="footer">
        <el-button type="primary" class="btn" @click="onSubmit" :loading="submitLoading">派遣</el-button>
        <el-button type="secondary" class="btn" @click.native.prevent="onCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { send } from '@common/api/worker';
import { getTenantList } from '@common/api/tenant';
import { getColumns } from '@common/utils/worker';
import { GENDER } from '@common/consts/worker';
import moment from 'moment';

export default {
  props: {
    visible: {
      type: Boolean,
      default() {
        return false;
      },
    },
    list: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  filters: {
    genderFilter(gender) {
      // 性别
      return gender ? GENDER.find(v => v.value === gender)?.label || '--' : '--';
    },
  },
  data() {
    return {
      loading: true,
      tenantList: [],
      sendForm: {
        tenantId: '',
        startTime: '',
        endTime: '',
      },
      formRules: {
        tenantId: [{ required: true, message: '请选择用工单位' }],
        startTime: [{ required: true, message: '请选择派遣开始时间' }],
        endTime: [{ required: true, message: '请选择派遣结束时间' }],
      },
      submitLoading: false,
    };
  },
  computed: {
    popVisible() {
      return this.visible;
    },
    columns() {
      return getColumns(['name', 'mobile', 'gender', 'age']);
    },
    startPickerOptions() {
      return {
        disabledDate: (time) => {
          if (this.sendForm.endTime) {
            return time.getTime() >= moment(this.sendForm.endTime) || time.getTime() < Date.now();
          }
          return time.getTime() < Date.now();
        },
      };
    },
    endPickerOptions() {
      return {
        disabledDate: (time) => {
          if (this.sendForm.startTime) {
            return time.getTime() <= moment(this.sendForm.startTime);
          }
          return time.getTime() < Date.now();
        },
      };
    },
  },
  watch: {
    popVisible() {
      if (this.popVisible) {
        this.fetchData();
      }
    },
  },
  methods: {
    async fetchData() {
      const res = await getTenantList({
        status: 'ALL',
      });
      if (res?.data?.tenants?.length) {
        this.tenantList = res.data.tenants;
        this.loading = false;
      } else {
        this.tenantList = [];
        this.loading = false;
      }
    },
    async onSubmit() {
      const params = {
        workers: this.list.map(v => ({ ...v, status: 'SEND' })),
        tenantId: this.sendForm.tenantId,
        startTime: this.sendForm.startTime,
        endTime: this.sendForm.endTime,
      };
      this.$refs.sendForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true;
          try {
            const response = await send(params);
            if (response?.code === 20000) {
              this.$emit('batchSendSuccess', true);
              this.$message({
                message: '派遣成功',
                type: 'success',
              });
              this.$refs.sendForm.resetFields();
            } else {
              this.$message({
                message: '派遣失败',
                type: 'warning',
              });
              this.$emit('batchSendHide');
              this.$refs.sendForm.resetFields();
            }
            this.submitLoading = false;
          } catch (error) {
            this.$message({
              message: JSON.stringify(error),
              type: 'warning',
            });
            this.submitLoading = false;
          }
        }
      });
    },
    onCancel() {
      this.$emit('batchSendHide');
      this.$refs.sendForm.resetFields();
    },
  },
};
</script>
